package com.ctgu.tengyun.util;

import com.ctgu.tengyun.exception.TengyunRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;

public class FileUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);
	public static final String FILE_SEPARATOR = System
			.getProperty("file.separator");
	
    public static final String BACKUP_FILE_PATTERN = "yyyyMMddHHmmss";
	
	private static final String TMP = "tmp.";
	
	private static final String ENCODING = "UTF-8";
	
	public static String fixPath(String path) {
		if (null != path && !path.endsWith(FILE_SEPARATOR)) {
			return path + FILE_SEPARATOR;
		}
		return path;
	}

    /**
     * 文件不存在返回null
     * @param filePath
     * @return
     */
    public static String getFileContent(String filePath){
    	File file = new File(filePath);
		if(!file.exists())
			return null;
		
        FileInputStream fstream = null;
        DataInputStream in = null;
        BufferedReader br = null;
        try {
            fstream = new FileInputStream(file);
            in = new DataInputStream(fstream);
            br = new BufferedReader(new InputStreamReader(in));

            String strLine;
            StringBuilder sb = new StringBuilder();
            while ((strLine = br.readLine()) != null) {
                sb.append(strLine);
            }
            return sb.toString();
        } catch (IOException e) {
			throw new TengyunRuntimeException("file not found", e);
		} finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {}
            }
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {}
            }
            if (null != fstream) {
                try {
                    fstream.close();
                } catch (IOException e) {}
            }
        }
    }
    
    public static void writeToFile(String filePath, String content) {
    	
    	String filePathTmp =  getTmpFilePath(filePath);
        FileWriter fWriter = null;
        BufferedWriter out = null;
        try {
        	File file = new File(filePathTmp);
    		if(!file.exists()){
    			file.createNewFile();
    		}
    		
            fWriter = new FileWriter(file);
            out = new BufferedWriter(fWriter);
            out.write(content);
            out.flush();
            
            File local =new File(filePath);
            file.renameTo(local);
        } catch (IOException ex) {
        	throw new TengyunRuntimeException("fail to write to file:" + filePath, ex);
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
            if (null != fWriter) {
                try {
                    fWriter.close();
                } catch (IOException e) {
                }
            }
        }
    }
    
//    public static <T> void writeToFile(Collection<T> values, String fileName,
//                                       Converter<T> converter, boolean append, boolean backup, boolean skipNull) {
//    	File file = new File(fileName);
//        String tempFileName = null;
//        if( backup && file.exists() ){
//        	renameToBackupFile(file);
//        }
//
//        if (append) {
//            tempFileName = fileName;
//        } else {
//        	tempFileName = getTmpFilePath(fileName);
//        }
//
//        File parent = file.getParentFile();
//        if (null != parent && !parent.exists()) {
//        	parent.mkdirs();
//        }
//
//        OutputStreamWriter writer = null;
//        try {
//        	 FileOutputStream fos = new FileOutputStream( tempFileName, append);
//        	 writer = new OutputStreamWriter(fos, ENCODING );
//        } catch (Exception e) {
//            throw new TengyunRuntimeException("failed to create " + tempFileName, e);
//        }
//
//        try {
//            for (T t : values) {
//            	String str = converter.convertToString(t);
//            	if( skipNull && str == null ) {
//            		continue;
//            	}
//                writer.write(str + "\n");
//            }
//        } catch (IOException ex) {
//            throw new TengyunRuntimeException("write to file " + tempFileName
//                    + " failed.");
//        } finally {
//            try {
//                writer.close();
//            } catch (IOException e) {
//            }
//        }
//
//        if ( !append ) {
//            File newFile = new File(fileName);
//            File tempFile = new File(tempFileName);
//            if (newFile.exists()) {
//                newFile.delete();
//            }
//
//            tempFile.renameTo(newFile);
//        }
//    }
    
    private static String getTmpFilePath(String fileName){
    	int index = fileName.lastIndexOf(FILE_SEPARATOR) + 1;
    	return fileName.substring(0, index) + TMP + fileName.substring(index);
    }
    private static boolean renameToBackupFile(File file) {
        Date date = new Date(file.lastModified());
        SimpleDateFormat sdf = new SimpleDateFormat(BACKUP_FILE_PATTERN);
        String newFilePath = file.getAbsolutePath() + "." + sdf.format(date);
        return file.renameTo(new File(newFilePath));
    }
    
    public static String getMd5ByFile(File file) {
    	FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			return org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
		} catch (FileNotFoundException e) {
			throw new TengyunRuntimeException("file not found", e);
		} catch (IOException e) {			
			throw new TengyunRuntimeException("calcuate md5 error", e);
		} finally {
			if( fis != null ) {
				try {
					fis.close();
				} catch (IOException ignore) {
					logger.warn("close stream failed.", ignore);
				}
			}
		}
    	
    }
}
